/*
 * Google Orb
 * Copyright Google, 2007-2008
 * Author: Jason Huggins (hugs@google.com)
 */

int incomingCommand = 0;
int incomingRedValue = 0;
int incomingGreenValue = 0;
int incomingBlueValue = 0;

int redPin   =  11;
int greenPin = 9;
int bluePin  = 10;

void setup()                   
{
  Serial.begin(9600);
}

void loop()
{
 // send data only when you receive data:
 if (Serial.available() >= 4) {
   // read the incoming byte:
   incomingCommand = Serial.read();
   incomingRedValue = Serial.read();
   incomingGreenValue = Serial.read();
   incomingBlueValue = Serial.read();


   if (incomingCommand == 48){    // int value of "0" (API: "set_colors")
     analogWrite(redPin, incomingRedValue); 
     analogWrite(greenPin, incomingGreenValue); 
     analogWrite(bluePin, incomingBlueValue); 
   }
   
   else if (incomingCommand == 49){ // int value of "1" (API: "fade_in")
      if (incomingRedValue > 0) {
        fadeIn(redPin);
      }
      if (incomingGreenValue > 0){
        fadeIn(greenPin); 
      }
      if (incomingBlueValue > 0){
        fadeIn(bluePin);
      }
   }

   else if (incomingCommand == 50){ // int value of "2" (API: "fade_out")
      if (incomingRedValue > 0) {
        fadeOut(redPin);
      }
      if (incomingGreenValue > 0){
        fadeOut(greenPin); 
      }
      if (incomingBlueValue > 0){
        fadeOut(bluePin);
      }
   }
   
    // say what you got:
    /* Only useful for debugging for now...
    Serial.print("Arduino received a command!: ");
    Serial.println(incomingCommand);
    Serial.print("Red Value: ");
    Serial.println(incomingRedValue);
    Serial.print("Green Value: ");
    Serial.println(incomingGreenValue);
    Serial.print("Blue Value: ");
    Serial.println(incomingBlueValue);      
    */ 
  }
}

void fadeIn(int pin)
{
  int value;
  for(value = 0 ; value <= 255; value+=5) // fade in (from min to max) 
  { 
    analogWrite(pin, value);           // sets the value (range from 0 to 255) 
    delay(30);                         // waits for 30 milli seconds to see the dimming effect 
  } 
}

void fadeOut(int pin)
{
  int value;
  for(value = 255; value >=0; value-=5)   // fade out (from max to min) 
  { 
    analogWrite(pin, value); 
    delay(30); 
  }  
}





